package com.example.xpvideo.service.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.xpvideo.entity.Admin;
import com.example.xpvideo.entity.ResponseResult;
import com.example.xpvideo.entity.req.LoginByPwdReq;
import com.example.xpvideo.entity.res.LoginRes;
import com.example.xpvideo.enums.ErrCodeEnum;
import com.example.xpvideo.exception.ErrorException;
import com.example.xpvideo.mapper.AdminMapper;
import com.example.xpvideo.service.AuthService;
import com.example.xpvideo.tools.Md5utils;
import com.example.xpvideo.tools.RedisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @author : 洪俊新
 * @date :  2021/4/25-17:19
 * @module
 */
@Service
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SqlSession sqlSession;

    @Override
    public ResponseResult<LoginRes> loginByPwd(LoginByPwdReq loginByPwdReq) throws ErrorException {
        String pwd = loginByPwdReq.getPwd();
        String account = loginByPwdReq.getAccount();
        String md5Pwd = Md5utils.getmd5Lowercase(pwd);
        Admin admin = adminMapper.selectOne(Wrappers.<Admin>lambdaQuery()
                .eq(Admin::getAccount, account)
                .last("limit 1"));
        if (ObjectUtils.isEmpty(admin)) {
            throw new ErrorException(ErrCodeEnum.unknown_10002);
        }

        if (!admin.getPwd()
                .equals(md5Pwd)) {
            throw new ErrorException(ErrCodeEnum.unknown_10002);
        }
        if(admin.getStage().equals(0)){
            throw new ErrorException(ErrCodeEnum.unknown_10013);
        }
        String token = UUID.randomUUID()
                .toString();
        redisUtil.set("xpvideo:admins:" + token, JSONObject.toJSONString(admin),
                24 * 60 * 60 * 3);
        LoginRes loginRes=new LoginRes();
        loginRes.setToken(token);
        loginRes.setNickname(admin.getNickname());
        loginRes.setImg(admin.getImg());
        return ResponseResult.responseResult(0, "登录成功", loginRes);
    }
}
